﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;

namespace BISPOS
{
    public partial class InvoiceDetailsUserControl : DevExpress.XtraEditors.XtraUserControl
    {
        Invoice Invoice;
        BISPOS.Repository.InvoiceRepository invoiceRepository = new Repository.InvoiceRepository();
        public InvoiceDetailsUserControl()
        {
            InitializeComponent();
        }
        public void ChangeInvoice(Invoice invoice)
        {
            Invoice = invoice;
            if (!Invoice.IsActive)
            {
                this.refundButton.Enabled = false;
                this.refundAllProductsButton.Enabled = false;
                this.simpleButton1.Enabled = false;
                this.labelControl1.Text = "ใบเสร็จถูกยกเลิก";
                this.labelControl1.ForeColor = Color.Red;
            }
            else
            {
                this.labelControl1.Text = "ใช้ใบเสร็จ";
                this.labelControl1.ForeColor = Color.Green;
                this.simpleButton1.Enabled = true;
            }
            this.simpleButton1.Text = "ยกเลิกใบเสร็จ";
            idTxtEdit.Text = Invoice.Id.ToString().PadLeft(8, '0');
            dateTextEdit.Text = String.Format("{0} - {1}", invoice.Date.ToShortTimeString(), invoice.Date.ToShortDateString());
            paymentTypeTextEdit.Text = invoice.PaymentType.FullText;
            if (invoice.CustomerId.HasValue)
                customerTextEdit.Text = invoice.Customer.Name;
            else
                customerTextEdit.Text = "ลูกค้าทั่วไป";
            employeeTextEdit.Text = invoice.Employee.Name;

            invoiceItemslinqServerModeSource.QueryableSource = invoice.InvoiceItems.AsQueryable();
            
            refundButton.Enabled = false;
            refundButton.Text = "คืนสินค้า (0)";
            refundAllProductsButton.Enabled = true;
            

            totalPriceTextEdit.Text = Invoice.TotalPrice.ToString("n2");
            invoiceItemsgridView.SelectRow(-1);

        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            try
            {
                ChangeInvoice(invoiceRepository.GetInvoice(Convert.ToInt32(searchFromIdtextEdit.Text)));
            }
            catch
            {
                MessageBox.Show("ไม่พบข้อมูลของใบกำกับภาษี : " + searchFromIdtextEdit.Text,"ผิดพลาด", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void invoiceItemsgridView_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            if (invoiceItemsgridView.SelectedRowsCount > 0)
            {
                refundButton.Enabled = true;
                refundButton.Text = "คืนสินค้า (" + invoiceItemsgridView.SelectedRowsCount.ToString() + ")";
            }
        }

        private void searchFromIdtextEdit_Enter(object sender, EventArgs e)
        {
            searchFromIdtextEdit.ResetText();
        }

        private void refundButton_Click(object sender, EventArgs e)
        {
            List<InvoiceItem> itemsToRemove = new List<InvoiceItem>();
            foreach (var item in invoiceItemsgridView.GetSelectedRows())
            {
                itemsToRemove.Add((InvoiceItem)invoiceItemsgridView.GetRow(item));
            }
            RefundProductsForm refundProductsForm = new RefundProductsForm(itemsToRemove, Invoice);
            refundProductsForm.Show();
        }

        private void refundAllProductsButton_Click(object sender, EventArgs e)
        {
            RefundProductsForm refundProductForm = new RefundProductsForm(Invoice.InvoiceItems.ToList(), Invoice);
            refundProductForm.Show();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                List<BISPOS.Report.DailyReportProduct> invoiceItems = new List<Report.DailyReportProduct>();
                foreach (var item in Invoice.InvoiceItems)
                {
                    string t = "";
                    if (item.Stock.Product.IsTaxed)
                        t = "#";

                    invoiceItems.Add(new Report.DailyReportProduct
                    {
                        Barcode = item.Stock.Product.Barcode,
                        Date = Invoice.Date,
                        IsTax = t,
                        Name = item.Stock.Product.Name,
                        Quantity = item.Quantity,
                        UnitPrice = item.Price.Amount
                    });
                }
                Report.SlipXtraReport report = new Report.SlipXtraReport();
                report.RequestParameters = false;
                report.DataSource = invoiceItems;

                if (!Invoice.PaymentType.IsCredit&&!Invoice.PaymentType.IsCaptitalPrice)
                {
                    report.billType.Value = "ใบเสร็จรับเงิน/ใบกำกับภาษี";
                    report.recieveperson.Value = "ผู้รับเงิน";
                    report.sendSign.Value = "ลงชื่อ";
                    report.sendPerson.Value = "ผู้รับสินค้า";
                }
                if (!Invoice.PaymentType.IsCaptitalPrice&&Invoice.PaymentType.IsCredit)
                {
                    report.billType.Value = "ใบกำกับภาษี/ใบส่งสินค้า";
                    report.sendSign.Value = "ลงชื่อ";
                    report.recieveperson.Value = "ผู้รับสินค้า";
                    report.sendPerson.Value = "ผู้ส่งสินค้า";

                }
                if (Invoice.PaymentType.IsCaptitalPrice && Invoice.PaymentType.IsCredit)
                {
                    report.billType.Value = "เดินสะพัดสาขา";
                    report.sendSign.Value = "ลงชื่อ";
                    report.recieveperson.Value = "ผู้รับสินค้า";
                    report.sendPerson.Value = "ผู้ส่งสินค้า";
                }

                if (Invoice.Customer != null)
                {
                    report.customer.Value = Invoice.Customer.Name;
                    report.address.Value = Invoice.Customer.Address;
                }



                report.date.Value = Invoice.Date.ToLongDateString();
                report.id.Value = Invoice.IdText;

                decimal sumExtVat =  Invoice.InvoiceItems.Where(x => !x.Stock.Product.IsTaxed).Sum(x =>
                    x.TotalPrice);
                decimal sumIncVat = Invoice.InvoiceItems.Where(x => x.Stock.Product.IsTaxed).Sum(x =>
                    x.TotalPrice);

                report.sumExtVat.Value = sumExtVat.ToString("N2");
                report.vat.Value = ((sumIncVat * 7) / 107).ToString("N2");
                report.sumIncVat.Value = (sumIncVat - ((sumIncVat*7)/107)).ToString("N2");

                report.ShowPreview();

            }
            catch { MessageBox.Show("ยังไม่ได้เลือกใบเสร็จ"); }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("ต้องการยกเลิกใบเสร็จ?", "ยกเลิก", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                invoiceRepository.VoidInvoice(Invoice.Id);
                ChangeInvoice(invoiceRepository.GetInvoice(Invoice.Id));
            }
        }
    }
}
